package cn.bone.alibabacloud.service.impl;

import cn.bone.alibabacloud.mapper.OrderMapper;
import cn.bone.alibabacloud.model.Order;
import cn.bone.alibabacloud.service.IAccountService;
import cn.bone.alibabacloud.service.IOrderService;
import cn.bone.alibabacloud.service.IStorageService;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
@Slf4j
public class OrderServiceImpl implements IOrderService {

    @Resource
    private OrderMapper orderMapper;
    @Resource
    private IAccountService accountService;
    @Resource
    private IStorageService storageService;

    /*
        name: 自定义名称，和其他的不要冲突即可
     */
    @Override
    @GlobalTransactional(name = "fsp-create-order", rollbackFor = Exception.class)
    public void create(Order order) {
        log.info("---> 开始新建订单");
        // 1.新建订单
        orderMapper.insert(order);

        log.info("---> 订单微服务开始调用库存，做扣减库存count");
        // 2.扣减商品库存
        storageService.decrease(order.getProductId(), order.getProductCount());
        log.info("---> 订单微服务开始调用库存，做扣减库存count\t end");

        log.info("---> 订单微服务开始调用账户，做扣减金额money");
        // 3.扣减账户余额
        accountService.decrease(order.getUserId(), order.getMoney());
        log.info("---> 订单微服务开始调用账户，做扣减金额money\t end");

        // 4.修改订单的状态，从0改成1
        log.info("---> 修改订单状态\t 开始");
        order.setOrderState(1);
        orderMapper.updateById(order);
        log.info("---> 修改订单状态\t 结束");

        log.info("---> 订单创建完成");
    }
}
